package controller

import (
	"errors"
	"testing"
	"time"

	"github.com/bluele/gcache"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)

func TestServerHealthCheck(t *testing.T) {
	testCases := []struct {
		name             string
		expiration       time.Duration
		httpChecker      HttpChecker
		cache            gcache.Cache
		numAccessToCache int
		wait             time.Duration
		want             bool
	}{
		{
			name:             "initial cache is empty server is responding update cache",
			expiration:       time.Second,
			httpChecker:      &dummyHttpServer{err: nil},
			cache:            gcache.New(1).LRU().Build(),
			want:             true,
			numAccessToCache: 1,
			wait:             time.Second * 0,
		},
		{
			name:             "server is responding read from cache",
			expiration:       time.Second,
			httpChecker:      &dummyHttpServer{err: nil},
			cache:            gcache.New(1).LRU().Build(),
			want:             true,
			numAccessToCache: 2,
			wait:             time.Second * 0,
		},
		{
			name:             "cache expire check with server",
			expiration:       time.Second,
			httpChecker:      &dummyHttpServer{err: nil},
			cache:            gcache.New(1).LRU().Build(),
			want:             true,
			numAccessToCache: 2,
			wait:             time.Second * 3,
		},
		{
			name:             "server is not responding",
			expiration:       time.Second,
			httpChecker:      &dummyHttpServer{err: errors.New("server is not available")},
			cache:            gcache.New(1).LRU().Build(),
			want:             false,
			numAccessToCache: 1,
			wait:             time.Second * 0,
		},
	}

	for _, tc := range testCases {
		t.Run(tc.name, func(t *testing.T) {
			for i := 0; i < tc.numAccessToCache; i++ {
				tsr := NewTrivyServerChecker(&tc.expiration, tc.cache, tc.httpChecker)
				got, err := tsr.TrivyServerAvaliable("serverURL")
				require.NoError(t, err)
				assert.Equal(t, tc.want, got)
				time.Sleep(tc.wait)
			}
		})
	}
}

type dummyHttpServer struct {
	err error
}

func (dhs dummyHttpServer) ServerHealthy(_ string) error {
	return dhs.err
}
